import { ipcMain } from "electron";
import { customerScriptContentDao, customerScriptDao } from "~/dao";
import { ListToTree } from "$/util/lang/TreeUtil";
import { beginTransactional } from "~/lib/db";

// 获取脚本树
ipcMain.handle("/api/customer_script/tree", async () => {
  const scripts = await customerScriptDao.selectList();
  return new ListToTree({
    idKey: "id",
    labelKey: "name",
    parentIdKey: "parent"
  }).transform(scripts);
});

// 新增脚本项
ipcMain.handle("/api/customer_script/add", async (_, payload) => {
  await customerScriptDao.insert(payload);
  await customerScriptContentDao.insertSelf({
    id: payload.id,
    content: ""
  });
});

// 重命名
ipcMain.handle("/api/customer_script/rename", async (_, payload) => {
  const { id, name } = payload;
  return await customerScriptDao.updateById(id, {
    name: name,
    updated_at: Date.now()
  });
});

// 删除
ipcMain.handle("/api/customer_script/delete", async (_, payload) => {
  const { id } = payload;
  await beginTransactional(async () => {
    await customerScriptDao.deleteById(id);
    await customerScriptContentDao.deleteById(id);
  });
});

// 获取脚本内容
ipcMain.handle("/api/customer_script/content/get", async (_, payload) => {
  const { id } = payload;
  const content = await customerScriptContentDao.selectById(id);
  return content?.content || "";
});

// 保存脚本内容
ipcMain.handle("/api/customer_script/content/save", async (_, payload) => {
  return await customerScriptContentDao.updateById(payload.id, {
    content: payload.content
  });
});
